import sqlite3
import os 
import nmapXmlHandler 
import sys
import xml.sax
import logging

'''
Created on 15 Mar 2010

@author: A Hopkins
'''

class DirectoryParser():
    
    # This class creates the database, and searches the directory structure for nmap files
    # It then sends those files to the nmap parser where the results are placed into the DB.
    def __init__(self, inputDirectory, dbOutputFile):
        self.dbOutputFile = dbOutputFile;
        self.inputDirectory = inputDirectory;
        self.parser = None
        self.handler = None
        
    
    def traverseDirectory(self, filenameStartsWith):
        for dirname, dirnames, filenames in os.walk(self.inputDirectory):       
            for filename in filenames:
                #if filenameStartsWith == "":
                if filename.endswith(".xml") and filename.startswith(filenameStartsWith): 
                    absoluteFilename = os.path.join(dirname, filename)
                    logging.info ("+ Parsing XML file: " + absoluteFilename)
                    #np = nmapParser.NmapParser(absoluteFilename, self.dbOutputFile);
                    self.initSax()
                    try:
                        self.parseXML(absoluteFilename)
                        #np.parseXML();
                    except IOError as strerror:
                        logging.error ("-- I/O error whilst parsing nmap XML file: \n" + absoluteFilename)
                        
    def initSax(self):
        self.parser = xml.sax.make_parser()
        self.handler = nmapXmlHandler.nmapXMLHandler(self.dbOutputFile)
        self.parser.setContentHandler(self.handler)
        
    def parseXML(self,absoluteFilename):
        try:
            self.parser.parse(absoluteFilename)
        except xml.sax._exceptions.SAXParseException as strerror:
            logging.error ("-- I/O ERROR - NmapParser.parseXML: " + str(strerror))
